package controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageInfo;

import domain.Message;
import service.IMessageService;

/**
 * @author Administrator
 *	留言板模块
 */
@Controller
public class GuestBookController {
	@Autowired
	private IMessageService service;

	@RequestMapping("/guestBook") //负责跳转到 留言板的界面 并且 读取数据库中的留言
	public String goGuestBook(HttpServletRequest req, Integer page) {
		Integer size = 6;//默认为一页4条数据
		if (page == null) {
			page = 1; //若请求中没有分页的信息 就从第一页开始
		}
		List<Message> all = service.listAll(page, size);
		PageInfo<Message> pageInfo = new PageInfo(all);
		//将pageInfo放到请求中做分页
		req.setAttribute("pageInfo", pageInfo);
		req.setAttribute("message", all);
		//防止表单重复提交
		String token = UUID.randomUUID().toString();
		req.setAttribute("tokenInform", token);
		req.getSession().setAttribute("tokenInSession", token);
		return "front/guestbook";
	}

	//这里不能直接返回视图 没有数据 可以重定向过去或者转发但是因为要共享是否留言成功所以。。。。
	@RequestMapping("/write")
	public void writeMsg(HttpServletRequest req, HttpServletResponse resp, String name, String link, String letter,
			String tokenInform) throws Exception {
		//这边执行收会转发到上面 所以session肯定不为空 可以toString
		String tokenInSession = (String)req.getSession().getAttribute("tokenInSession");
		if (tokenInform.equals(tokenInSession)) {
			Message msg = new Message();
			msg.setContent(letter);
			msg.setMsgDate(new Date());
			msg.setName(name);
			msg.setQqNumber(link);
			msg.setMsgIp(req.getRemoteAddr());
			Integer state = service.write(msg);
			if (state > 0) {
				req.setAttribute("isSuccess", "留言成功");
			} else {
				req.setAttribute("isSuccess", "留言失败");
			}
			req.getSession().invalidate();
		}
		req.getRequestDispatcher("/guestBook").forward(req, resp);
	}
}
